/**
 *
 */
package com.jdy.haoduoai.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.activity.BreathLightActivity;
import com.jdy.haoduoai.activity.ChoiceActivity;
import com.jdy.haoduoai.activity.DevicePropertyActivity;
import com.jdy.haoduoai.activity.RadioStationActivity;
import com.jdy.haoduoai.activity.SpeakForYouActivity;
import com.jdy.haoduoai.activity.TabTellStoryActivity;
import com.jdy.haoduoai.enums.MediaType;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.CategoryItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.RadioCategoryItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.socket.DeviceStateListener;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.visualizer.FrequencyDistributionBarView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.view.magicindicator.buildins.UIUtil;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class TabNewDiscoverFragment extends BaseFragment implements
        OnClickListener, DeviceStateListener,
        OnDataReceivedListener {

    private static final String TAG = TabNewDiscoverFragment.class
            .getSimpleName();

    @InjectView(id = R.id.baby_story_machine, click = true)
    private ImageView mBabyMachineImg;
    @InjectView(id = R.id.story_babysong_diy, click = true)
    private ImageView mStoryBabySongDIYImg;
    @InjectView(id = R.id.speak_for_u, click = true)
    private ImageView mSpeakForYouImg;
    @InjectView(id = R.id.breathe_light_img, click = true)
    private ImageView mBreathLightImg;
    @InjectView(id = R.id.ar_interactive_img, click = true)
    private ImageView ar_interactive_img;
    @InjectView(id = R.id.new_finder_back_ib, click = true)
    private ImageButton mBackIB;
    @InjectView(id = R.id.device_stateview, click = true)
    private FrequencyDistributionBarView device_stateview;

    //课文朗读
    @InjectView(id = R.id.ll_kwld, click = true)
    private LinearLayout llKwld;
    @InjectView(id = R.id.lv_kwld)
    private ImageView lvKwld;


    //故事DIY
    @InjectView(id = R.id.ll_gsdiy, click = true)
    private LinearLayout llGsdiy;
    @InjectView(id = R.id.lv_gsdiy)
    private ImageView lvGsdiy;

    //金牌新概念
    @InjectView(id = R.id.ll_jpxgl, click = true)
    private LinearLayout llJpxgl;
    @InjectView(id = R.id.lv_jpxgl)
    private ImageView lvJpxgl;


    //课外阅读,对应原有的宝宝故事机
    @InjectView(id = R.id.ll_kwyd, click = true)
    private LinearLayout llKwyd;

    @InjectView(id = R.id.lv_kwyd)
    private ImageView lvKwyd;

    //故事DIY
    @InjectView(id = R.id.ll_tnfs, click = true)
    private LinearLayout llTnfs;
    @InjectView(id = R.id.lv_tnfs)
    private ImageView lvTnfs;

    //屏幕宽高
    private int screenWidth;
    private int screenHeight;

    //线性布局布局参数
    private LinearLayout.LayoutParams llLp;

    //顶部和底部的图片宽高
    private int topAndBottomImgSize;

    //中间对图片宽高
    private int centerImgSize;

    //帧动画对象
    private AnimationDrawable anim;

    private void bindService() {
        SocketThreadManager.getInstance().setDataReceivedListener(TabNewDiscoverFragment.this);
        SocketThreadManager.getInstance().setDeviceStateListener(TabNewDiscoverFragment.this);

        try {
            JSONObject dataJson = new JSONObject();
            dataJson.put("code", 202);
            dataJson.put("act", "machineinfo");
            SocketThreadManager.getInstance().send(dataJson.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //数据集合
    private List<RadioCategoryItem> mRadioCategoryList;

    private LeUser mLeUser;


    private CategoryItem categoryItem;

    @SuppressLint("ValidFragment")
    public TabNewDiscoverFragment(BaseActivity ba) {
    }

    public TabNewDiscoverFragment() {
    }

    @Override
    public void onDestroy() {

        SocketThreadManager.getInstance().removeDataReceivedListener(TabNewDiscoverFragment.this);
        SocketThreadManager.getInstance().removeDeviceStateListener(TabNewDiscoverFragment.this);

        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }


        if (anim != null) {
            if (anim.isRunning()) {
                anim.stop();
            }
            anim = null;
        }
        super.onDestroy();
    }

    @Override
    public View onCreateView(Bundle savedInstanceState, LayoutInflater inflater,
                             ViewGroup container) {
        View bodyView = LayoutInflater.from(mContext).inflate(
                R.layout.new_finder_layout, container, false);

        return bodyView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mLeUser = ((LeXiaoXiaoBanApp) getActivity().getApplication()).getUser();

        mBabyMachineImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
        mStoryBabySongDIYImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
        mSpeakForYouImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
        mBreathLightImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
        ar_interactive_img.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

        bindService();

        //初始处理,用于对屏幕中的图片作适配性处理
        adaptiveScreen();

        //请求页面数据
        loadCategoryData();
    }

    /**
     * 对页面做动态适配处理
     */
    private void adaptiveScreen() {
        screenHeight = UIUtil.getScreenHeight(getContext());
        int topAndBottomHeight = screenHeight * 2 / 7 * 3 / 7;
        llLp = new LinearLayout.LayoutParams(topAndBottomHeight, topAndBottomHeight);
        lvKwld.setLayoutParams(llLp);
        lvGsdiy.setLayoutParams(llLp);
        lvKwyd.setLayoutParams(llLp);
        lvTnfs.setLayoutParams(llLp);

        int centerHeight = screenHeight * 2 / 7 * 3 / 2 * 3 / 5;
        llLp = new LinearLayout.LayoutParams(centerHeight, centerHeight);
        lvJpxgl.setLayoutParams(llLp);

        //给金牌新概念设置帧动画处理
        lvJpxgl.setBackgroundResource(R.drawable.anim_jpxgl);
        anim = (AnimationDrawable) lvJpxgl.getBackground();
        anim.start();
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.baby_story_machine:
            case R.id.ll_kwyd:
                //宝宝故事机
                intent.setClass(mContext, RadioStationActivity.class);
                startActivity(intent);
                break;

            case R.id.story_babysong_diy:
            case R.id.ll_gsdiy:
                intent.setClass(mContext, TabTellStoryActivity.class);
                startActivity(intent);
                break;
            case R.id.speak_for_u:
            case R.id.ll_tnfs:
                //替你发声
                intent.setClass(mContext, SpeakForYouActivity.class);
                startActivity(intent);
                break;
            case R.id.breathe_light_img:
                intent = new Intent(mContext, BreathLightActivity.class);
                startActivity(intent);
                break;
            case R.id.ar_interactive_img:
                break;
            case R.id.new_finder_back_ib:
                break;
            case R.id.device_stateview:
                intent.setClass(mContext, DevicePropertyActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_jpxgl:
                //跳转到金牌新概念
                goChocieActivity("金牌新概念");
                break;

            case R.id.ll_kwld:
                //跳转到课文朗读
                goChocieActivity("课文朗读");
                break;
            default:
                break;
        }
    }

    /**
     * 跳转到ChocieActivity的方法
     */
    private void goChocieActivity(String name) {
        for (int i = 0; i < mRadioCategoryList.size(); i++) {
            if (name.equals(mRadioCategoryList.get(i).name)) {
                categoryItem = convert2CI(mRadioCategoryList.get(i));
                break;
            }
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        intent.setClass(mContext, ChoiceActivity.class);
        bundle.putSerializable("categoryitem", categoryItem);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private Handler mHandler = new Handler();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

            LeConfig.isInternetAvailable = Tools.isNetworkAvailable(getActivity());

            if (!LeConfig.isDeviceConnect && device_stateview != null) {
                device_stateview.setPlaying(false);
            }


            if (!LeConfig.isInternetAvailable) {
                device_stateview.setPlaying(false);
            }

            SocketThreadManager.getInstance().setDataReceivedListener(TabNewDiscoverFragment.this);
            SocketThreadManager.getInstance().setDeviceStateListener(TabNewDiscoverFragment.this);

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("code", 202);
                        jsonObject.put("act", "videostatu");
                        SocketThreadManager.getInstance().send(jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 500);
            //对动画做处理
            if (anim == null) {
                anim = (AnimationDrawable) lvJpxgl.getBackground();
                anim.start();
            }
        } else {
            if (anim != null) {
                if (anim.isRunning()) {
                    anim.stop();
                }
                anim = null;
            }
        }
    }

    @Override
    public void onRemoteLogin() {
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                device_stateview.setPlaying(false);
            }
        });
    }

    @Override
    public void onConnectionChanged(boolean connect) {
    }

    @Override
    public void onPowerChanged(int power) {
    }

    @Override
    public void onUpgrade(int updatingStatus) {

    }

    @Override
    public void onCheckDeviceVersion(String version) {

    }

    @Override
    public void onPlayNextFailed() {
    }

    @Override
    public void onPlayPrevFailed() {
    }

    @Override
    public void onPlayMedia(final PlayState playState, MediaType type,
                            JSONObject data) {
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (playState.equals(PlayState.Playing)) {
                    device_stateview.setPlaying(true);
                } else {
                    device_stateview.setPlaying(false);
                }

            }
        });
    }

    @Override
    public void onReceivedVoiceMessage(String streamUrl) {
    }

    @Override
    public void onDataReceived(String data) {
    }

    /**
     * 获取页面数据
     */
    private void loadCategoryData() {

        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    if (Tools.isNotEmpty(result.data)) {
                        parseJsonArray(result.data);
                    }
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {

                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<>();
                param_.put("sno", mLeUser.sno);
                param_.put("t_cate", "1");
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/catalog/radio/collection", param_,
                        HttpUtils.TAG_GET_REQUEST);

            }
        }).execute();

    }

    /**
     * 解析返回的JSON数据
     *
     * @param data
     */
    private void parseJsonArray(String data) {
        mRadioCategoryList = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(data);

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jo = (JSONObject) jsonArray.get(i);

                RadioCategoryItem rci = JsonSerializer.getInstance().deserialize(
                        jo.toString(), RadioCategoryItem.class);

                mRadioCategoryList.add(rci);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将RadioCategoryItem转化为CategoryItem对象
     *
     * @param rci
     * @return
     */
    private CategoryItem convert2CI(RadioCategoryItem rci) {
        CategoryItem ci = new CategoryItem();
        ci.id = rci.id;
        ci.name = rci.name;
        ci.code = rci.code;
        if (rci.enabled)
            ci.enabled = 1;
        else
            ci.enabled = 0;
        ci.sort = rci.sort;
        ci.created_at = rci.created_at;
        ci.updated_at = rci.updated_at;
        ci.deleted_at = rci.deleted_at;
        ci.icon = rci.icon;
        ci.catalog = rci.catalog;
        ci.home_page = rci.home_page;
        return ci;
    }

}
